#include "stm32l4xx_hal.h"
#include "borad.h"
#include "delay.h"
#include "sys.h"
#include "lcd.h"
#include "usart.h"
#include "wdg.h"
#include <string.h>

uint8_t Num = 0;

void HAL_GPIO_EXTI_Callback(uint16_t GPIO_Pin);
void process_command(char* cmd);
void usart_receive_handler(void);

int main(void)
{
    uint8_t r,g,b;
    HAL_Init();
    sys_stm32_clock_init(20);
    delay_init(80); //80MHZ
    led_init();
    LED_Init();
    lcd_init();
    key_init();
    usart_init(9600);
    wwdg_init(0x7F,0x5F,16);
    printf("USART Test Started!\r\n");
    printf("Supported commands: Num++, Num--,LED\r\n");

    while (1)
    {
        // 打印系统频率
        lcd_printf(1,1,LCD_FONT_16,"SYSCLK: %dMHz",HAL_RCC_GetHCLKFreq() / 1000000,2);
        lcd_printf(2,1,LCD_FONT_16,"RGB: 0x");
        lcd_show_hexNum(8*(8-1),16*(2-1),rgb565_encode(r,g,b),4,LCD_FONT_16,NUM_SHOW_ZERO,g_point_color);
        
        lcd_printf(3,1,LCD_FONT_16,"Num: %u",Num);
        // 处理串口接收数据
        usart_receive_handler();
        r+=3;
        g+=2;
        b++;
        led_rgb565(rgb565_encode(r,g,b));
    }
}

/**
 * @brief  中断服务程序中需要做的事情
           在HAL库中所有的外部中断服务函数都会调用此函数
 * @param  GPIO_Pin:中断引脚号
 * @retval 无
 */
void HAL_GPIO_EXTI_Callback(uint16_t GPIO_Pin)
{
    if(GPIO_Pin == KEY_1.pin)
    {
        Num += 1;

    }
    else if(GPIO_Pin == KEY_2.pin)
    {
        Num += 2;
    }
}

/**
 * @brief  处理串口命令
 * @param  cmd: 接收到的命令字符串
 * @retval 无
 */
void process_command(char* cmd) {
    // 移除字符串末尾的换行符和回车符
    int len = strlen(cmd);
    while(len > 0 && (cmd[len-1] == '\r' || cmd[len-1] == '\n')) {
        cmd[len-1] = '\0';
        len--;
    }
    
    // 解析命令
    if(strcmp(cmd, "Num++") == 0) {
        Num++;
        printf("Num increased to %d\r\n", Num);
    }
    else if(strcmp(cmd, "Num--") == 0) {
        Num--;
        printf("Num decreased to %d\r\n", Num);
    }
    else if(strcmp(cmd, "LED") == 0) {
        HAL_GPIO_TogglePin(LED.GPIOx,LED.pin);
        printf("LED had toggle\r\n");
    }
    else {
        printf("Unknown command: %s\r\n", cmd);
        printf("Supported commands: Num++, Num--,LED\r\n");
    }
}

void usart_receive_handler(void)
{
    if(uart_rx_available() > 0){
        char cmd_buffer[20];
        
        /* 先尝试查找命令 */
        if (uart_find_command(cmd_buffer, sizeof(cmd_buffer))) {
            // 命令已经被处理并从缓冲区移除，现在回显命令内容
            process_command(cmd_buffer);
        } else {
            /* 没有完整命令，只回显新到达的字符 */
            while (uart_rx_available() > 0) {
                int16_t data = uart_rx_read();
                if (data >= 0) {
                    uint8_t ch = (uint8_t)data;
                    /* 回显到串口 */
                    HAL_UART_Transmit(&g_uart_handle, &ch, 1, 10);
                    while(HAL_UART_GetState(&g_uart_handle) == HAL_UART_STATE_BUSY_TX);
                }else{
                    printf(" is not find.\r\n");
                }
            }
        }
    }
}
